#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :get_jingdong_delete_order.py
# Time  :广州总公司-广州子公司-2025/3/11 13:38
# Email :fortunatedong@163.com
# Author:by Adonli
import copy
import json
import os
import random
import time
from datetime import datetime

import pandas as pd
import requests

import toml
from decimal import getcontext, Decimal
import re

from jingdong_order_synchronization_kuaipu_zhuzhanghao.analyze_datas.save_delete_jingdong_synchronization_datas import \
    SaveDeleteJingdongSynchronizationDatas
from jingdong_order_synchronization_kuaipu_zhuzhanghao.settings.logger import Loggings
from jingdong_order_synchronization_kuaipu_zhuzhanghao.synchronization_kuaipu.search_shop_supply_map_api import get_SearchShopSupplyMap_datas
from jingdong_order_synchronization_kuaipu_zhuzhanghao.synchronization_kuaipu.synchronization_kuaipu_order_api import SynchronizationKuaiPuOrderApi
from jingdong_order_synchronization_kuaipu_zhuzhanghao.dingding_robot.messages_push import  MessagePush
from jingdong_order_synchronization_kuaipu_zhuzhanghao.analyze_datas.save_jingdong_synchronization_datas import SaveJingdongSynchronizationDatas
from jingdong_order_synchronization_kuaipu_zhuzhanghao.settings.error_handler import retry_on_exception
logs = Loggings()
class get_jingdong_delete_order_datas():
    def __init__(self, username, password, startTime, endTime,jingdong_cookie):
        self.username = username
        self.password = password
        self.jingdong_cookie = jingdong_cookie
        self.cfg = toml.load('settings/config.toml')
        self.order_url = self.cfg['JINGDONGORDERURL']['order_url']
        self.headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "cookie": self.jingdong_cookie,
        }
        self.payload = {
            "startTime": startTime,
            "endTime": endTime,
            "_search": "false",
            "nd": int(round(time.time() * 1000)),
            "rows": 100,
            "page": 1,
            "sidx": "orderId asc, groupString asc,",
            "sord": "asc",
            "orderId": "",
            "sku": "",
            "poId": "",
            "roId": "",
            "shipNo": "",
            "phone": "",
            "orderState": 29,
            "businessType": "",
            "pin": "",
            "paymentType": "",
            "vendorStoreId": "",
            "ouId": "",
        }


    def json_to_cookie(self,json_data):
        # 提取name和value对,并用=连接
        cookie_pairs = [f"{cookie['name']}={cookie['value']}" for cookie in json_data]

        # 用分号和空格连接所有cookie对
        cookie_string = "; ".join(cookie_pairs)

        return cookie_string

    @retry_on_exception(max_retries=3, delay=2)
    def get_jingdong_order_json(self):

        response = requests.post(self.order_url, headers=self.headers, data=self.payload)
        if response.status_code == 200:
            logs.info(f"请求京东订单接口成功；状态值为{response.status_code}")
        else:
            logs.info(f"请求京东订单接口失败；状态值为{response.status_code}")
        # logs.info(f"datas_json:{response.json()}")
        datas_json = response.json()["rows"]

        if datas_json:
            logs.info(f"已获取{len(datas_json)}京东订单")
        else:
            logs.debug("未获取到京东订单")
        return datas_json

    @retry_on_exception(max_retries=3, delay=2)
    def handle_jingdong_order_json(self):
        datas_json = self.get_jingdong_order_json()
        detail_consignee_name_address = "https://pdropship.jd.com/virtualNumber/getConsigneeInfo"
        detail_consignee_phone = "https://pdropship.jd.com/virtualNumber/bindVirtualNumber"
        jingdong_orders_messages = []
        for data in datas_json:
            jingdong_order_id = data["orderId"]
            form_data = {
                "orderId": jingdong_order_id,
            }
            detail_consignee_name_address_response = requests.post(detail_consignee_name_address, headers=self.headers,
                                                                   data=form_data)
            detail_consignee_name_addres_json = detail_consignee_name_address_response.json()["userdata"][
                "consigneeInfo"]
            jingdong_consignee_name = re.sub(r"\[[^\]]*\]", "",
                                             detail_consignee_name_addres_json["consigneeName"])
            jingdong_consignee_address = re.sub(r"\[[^\]]*\]", "",
                                                detail_consignee_name_addres_json[
                                                    "consigneeAddress"])
            detail_consignee_phone_response = requests.post(detail_consignee_phone, headers=self.headers,
                                                            data=form_data)
            detail_consignee_phone_json = detail_consignee_phone_response.json()["userdata"]["virtualNumberInfo"]
            jingdong_phone = detail_consignee_phone_json["virtualNumber"]
            order_create_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(data["orderCreateDate"] / 1000))

            add_jingdong_order = {
                "branch_id": "金穗隆(广州)信息科技有限公司",
                "jingdong_business_model": "电商销售",
                "jingdong_order_id": jingdong_order_id,
                "jingdong_consignee_name": jingdong_consignee_name,
                "jingdong_consignee_address": jingdong_consignee_address,
                "jingdong_phone": jingdong_phone,
                "order_create_date": order_create_date
            }
            add_jingdong_order_body = []
            for detail_data in data["orderDetailList"]:
                jd_price = detail_data['jdPrice']
                procurement_single_price = detail_data["poPrice"]
                ware_num = detail_data["wareNum"]
                jd_total_price = jd_price * ware_num
                procurement_total_price = procurement_single_price * ware_num
                ware_name = detail_data["wareName"]
                sku = detail_data["sku"]
                add_jingdong_order_dict = {
                    # "jingdong_ware_name": ware_name,
                    "jingdong_sku": sku,
                    "jingdong_ware_brand": "",
                    "jingdong_ware_category": "",
                    "jingdong_ware_model": "",
                    "jingdong_ware_num": ware_num,
                    "jingdong_jd_price": jd_price,
                    "jingdong_jd_total_price": jd_total_price,
                    "jingdong_procurement_single_price": procurement_single_price,
                    "jingdong_procurement_total_price": procurement_total_price,
                }
                add_jingdong_order_body.append(add_jingdong_order_dict)
            requests_dict = {
                "add_jingdong_order": add_jingdong_order,
                "add_jingdong_order_bodys": {
                    "add_jingdong_order_body": add_jingdong_order_body
                }
            }
            jingdong_orders_messages.append(requests_dict)
        logs.info(f"jingdong_orders_messages:{jingdong_orders_messages}")
        # print(jingdong_orders_messages)
        return jingdong_orders_messages

    def check_delete_datas(self,jingdong_order_id,order_create_date):
        date_obj = datetime.strptime(order_create_date, '%Y-%m-%d %H:%M:%S')
        current_year = date_obj.year
        current_month = date_obj.month
        directory = f'analyze_datas/jingdongorders/广州总公司-{current_year}'
        csv_file = f'analyze_datas/jingdongorders/广州总公司-{current_year}/广州总公司-{current_year}-{current_month}-delete.csv'
        # logs.info(f"current_year:{current_year},current_month:{current_month},directory:{directory},csv_file:{csv_file}")
        if not os.path.exists(directory):
            return False
        if not os.path.exists(csv_file):
            return False
        else:
            df = pd.read_csv(csv_file)
            # print(df['jingdong_order_id'])
            check_jingdong_order_id = df['jingdong_order_id'].isin([int(jingdong_order_id)]).any()
            # print(check_jingdong_order_id)
            return check_jingdong_order_id



    def delete_jingdong_order(self):
        delete_synchronization_orders_messages = []
        jingdong_orders_messages = self.handle_jingdong_order_json()
        for jingdong_order_message in jingdong_orders_messages:
            delete_synchronization_orders_messages.append(jingdong_order_message)
            logs.info(f"delete_synchronization_orders_messages:{delete_synchronization_orders_messages}")
        if delete_synchronization_orders_messages:
            for i in delete_synchronization_orders_messages:
                delete_synchronization_json_data = json.dumps({"request": i}, ensure_ascii=False)
                delete_synchronization_dict_data = json.loads(delete_synchronization_json_data)
                jingdong_order_id = delete_synchronization_dict_data['request']['add_jingdong_order']['jingdong_order_id']
                order_create_date = delete_synchronization_dict_data['request']['add_jingdong_order']['order_create_date']
                logs.info(f"jingdong_order_id:{jingdong_order_id},order_create_date:{order_create_date}")
                check_jingdong_order_id = self.check_delete_datas(jingdong_order_id,order_create_date)
                logs.info(f"jingdong_order_id:{jingdong_order_id},check_jingdong_order_id:{check_jingdong_order_id}")
                if not check_jingdong_order_id:
                    SaveDeleteJingdongSynchronizationDatas(delete_synchronization_dict_data).save_delete_synchronization_orders_messages()
                    MessagePush(delete_synchronization_dict_data).delete_text_push()
                    logs.info(f"delete_synchronization_dict_data:{delete_synchronization_dict_data}")
                    time.sleep(1)
#
#
# with open("../auth/jingdong_cookies.json", "r") as f:
#     cookie_data = json.load(f)
#     jsessionid_list = []
#     # for cookie in cookie_data:
#     #     print(cookie)
#     #     if cookie["name"] == "JSESSIONID":
#     #         print(cookie["value"])
#     JSESSIONID = [cookie["value"] for cookie in cookie_data if cookie["name"] == "JSESSIONID"]
#     flash = [cookie["value"] for cookie in cookie_data if cookie["name"] == "flash"]
#     jingdong_cookie = f"flash={random.choice(flash)};JSESSIONID={random.choice(JSESSIONID)};"
# if __name__ == '__main__':
#
#     get_jingdong_delete_order_datas('xxxxxxxxxxxxx',
#                             'xxxxxxxxxxxxxxxxxx',
#                             '广州总公司-广州子公司-2025-03-01 00:00:00',
#                             '广州总公司-广州子公司-2025-03-11 12:50:00',
#                             jingdong_cookie
#     ).delete_jingdong_order()
